package com.zp.base.admin.security;

import com.zp.base.admin.dao.UserDao;
import com.zp.base.admin.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhangpeng
 */
@Service("permissionService")  //自定义注解式授权
public class PermissionService {
    @Autowired
    private UserDao userDao;

    public final boolean hasAuthority(String authority) {
        return this.hasAnyAuthority(authority);
    }

    public final boolean hasAnyAuthority(String... authorities) {
        //获取用户id
        Long id = getId();
        //根据用户名获取所有权限
        List<String> list = userDao.findPermissionsByUserId (id);
        for (String authority : authorities) {
            if (list.contains (authority)){
                return true;
            }
        }
        return false;
    }

    public final boolean hasRole(String role) {
        return this.hasAnyRole(role);
    }

    public final boolean hasAnyRole(String... roles) {
        Long id = getId();
        List<String> list = userDao.findRolesByUserId (id);
        for (String role : roles) {
            if (list.contains (role)){
                return true;
            }
        }
        return false;
    }


    public Long getId(){
        UserEntity userEntity = (UserEntity) SecurityContextHolder.getContext ().getAuthentication ().getPrincipal ();
        return userEntity.getId ();
    }


}
